package com.mfl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mfl.common.PageResult;
import com.mfl.constant.MessageConstant;
import com.mfl.context.BaseContext;
import com.mfl.exception.BannerAlreadyExistsException;
import com.mfl.mapper.BannerMapper;
import com.mfl.pojo.dto.BannerDTO;
import com.mfl.pojo.dto.BannerPageQueryDTO;
import com.mfl.pojo.entity.Banner;
import com.mfl.pojo.vo.BannerPageQueryVO;
import com.mfl.pojo.vo.BannerVO;
import com.mfl.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BannerServiceImpl implements BannerService {

    @Autowired
    private BannerMapper bannerMapper;

    /**
     * 分页查询轮播图
     *
     * @param bannerPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(BannerPageQueryDTO bannerPageQueryDTO) {
        PageHelper.startPage(bannerPageQueryDTO.getPage(), bannerPageQueryDTO.getPageSize());
        Page<BannerPageQueryVO> page = bannerMapper.pageQuery(bannerPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增轮播图
     *
     * @param bannerDTO
     */
    @Override
    public void insert(BannerDTO bannerDTO) {
        // 查询轮播图标题是否存在
        Banner b = bannerMapper.getByTitle(bannerDTO.getTitle());
        if (b != null) {
            throw new BannerAlreadyExistsException(MessageConstant.BANNER_ALREADY_EXISTS);
        }
        Banner banner = Banner.builder()
                .title(bannerDTO.getTitle())
                .url(bannerDTO.getUrl())
                .status(bannerDTO.getStatus())
                .createTime(LocalDateTime.now())
                .createUser(BaseContext.getCurrentId())
                .build();
        bannerMapper.insert(banner);
    }

    /**
     * 批量删除轮播图
     *
     * @param ids
     */
    @Override
    public void batchDelete(List<Integer> ids) {
        bannerMapper.deleteByIds(ids);
    }

    /**
     * 修改轮播图状态
     *
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, Integer id) {
        bannerMapper.updateStatus(status, id);
    }

    /**
     * 获取轮播图列表
     *
     * @return
     */
    @Override
    public List<BannerVO> getBannerList() {
        List<Banner> bannerList = bannerMapper.getBannerList();
        return bannerList.stream().map(banner -> BannerVO.builder()
                .id(banner.getId())
                .title(banner.getTitle())
                .url(banner.getUrl())
                .build()).toList();
    }
}
